package com.epam.facebook_client.fragment;

import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.epam.facebook_client.R;
import com.epam.facebook_client.api.API;
import com.epam.facebook_client.manager.ImageManager;
import com.epam.facebook_client.task.JSONObjectAsyncTask;
import com.epam.facebook_client.wrapper.User;

public class HeadFragment extends Fragment {

	protected static final String TAG = HeadFragment.class.getSimpleName();
	public static final String MY_ID = "MY_ID";
	public static final String ID = "ID";

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View inflate = inflater.inflate(R.layout.fragment_head, container, false);
		final ImageView imageViewUser = (ImageView) inflate.findViewById(R.id.userImage);
		final TextView textViewName = (TextView) inflate.findViewById(R.id.userName);
		final ImageManager imageManager = ImageManager.get(getActivity());

		
		
		new JSONObjectAsyncTask<User>(getActivity()) {

			@Override
			protected User create(String json) {
				return new User(json);
			}

			@Override
			protected void success(User user) {
				imageManager.loadImage(API.getPictureSquare(user.getId()), imageViewUser);
				textViewName.setText(user.getName());
				Editor edit = getActivity().getSharedPreferences(MY_ID, 0).edit();
				edit.putString(ID, user.getId());
				edit.commit();
/*				ContentValues value = new ContentValues();
				value.put("data", user.toString());
				int update = getActivity().getContentResolver().update(AppContract.FriendsColumns.CONTENT_URI, value,
						"_id = ?", new String[] { user.getId() });
				if(update == 0){
					getActivity().getContentResolver().insert(AppContract.FriendsColumns.CONTENT_URI, value);
				}*/
			}

			@Override
			protected void onError(Exception e) {
				Log.e(TAG, "Exception: " + e);
				Toast.makeText(getActivity(), e.getMessage(), Toast.LENGTH_LONG).show();
			}
		}.execute(API.ME_HEAD);
		
		
		return inflate;
	}
}
